package com.cn.utlis;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by chenyuncong on 2018/9/14.
 */
@Component
public class FreeMarkerUtils {

    @Autowired
    protected freemarker.template.Configuration configuration;

    private String outPath = "D:\\testData\\freemarker_out\\";

    public void createFile(String templateName, String outFileName, Map root) throws Exception {
        Template temmplate = configuration.getTemplate(templateName);
        write(temmplate, outFileName, root);
    }

    //6 获取io流     输出     关流
    private void write(Template temmplate, String fileName, Map root) throws Exception {
        Writer out = new FileWriter(new File(outPath+fileName));
        temmplate.process(root, out);
        out.flush();
        out.close();
    }

    public static String upperCharToUnderLine(String param) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || param.equals("")) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {
            builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
            i++;
        }

        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }

    //首字母大写
    public static String captureName(String name) {
        char[] cs = name.toCharArray();
        if(cs[0] > 96 && cs[0] < 123) {
            cs[0] -= 32;
        }
        return String.valueOf(cs);
    }
    //首字母大写
    public static String smallName(String name) {
        char[] cs = name.toCharArray();
        if(cs[0] > 64 && cs[0] < 91) {
            cs[0] += 32;
        }
        return String.valueOf(cs);
    }

    public static void main(String[] args) {
        System.out.println(upperCharToUnderLine("UserAndEmailInfo"));
        System.out.println(captureName("UserInfo"));
    }
}
